package com.waves.message.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.rabbitmq.client.Channel;
import com.waves.core.constant.MQConstant;
import com.waves.core.constant.redis.UserRedisKey;
import com.waves.core.utils.RedisUtils;
import com.waves.core.web.domain.dto.MessageRecordInsertDTO;
import com.waves.message.domain.entity.MessageRecord;
import com.waves.message.service.MessageRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 消息中心给每位用户发送一条通知
 *
 * @author wangzhiwei
 * @date 2023/10/29 09:08
 **/
@Component
@Slf4j
public class MessageRabbitListener {

    @Resource
    private MessageRecordService messageRecordService;

    @RabbitListener(queues = MQConstant.MESSAGE_RECORD_QUEUE)
    public void listener(MessageRecordInsertDTO dto, Channel channel, Message msg) throws JsonProcessingException {
        // 当消息类型是任务通知，通知发帖人的所有粉丝
        if (1 == dto.getMessageType()) {
            String key = UserRedisKey.getKey(UserRedisKey.USER_FOLLOWED_SET, dto.getUserId());
            Set<String> sets = RedisUtils.sGet(key);
            assert sets != null;
            for (String set : sets) {
                dto.setReceiveUserId(Long.valueOf(set));
                int count = messageRecordService.count(new LambdaQueryWrapper<MessageRecord>()
                                .eq(MessageRecord::getTaskId, dto.getTaskId())
                                .eq(MessageRecord::getNoticeType, dto.getNoticeType())
                                .eq(MessageRecord::getMessageType, dto.getMessageType())
                                .eq(MessageRecord::getReceiveUserId, dto.getReceiveUserId()));
                if (count == 0) {
                    messageRecordService.insert(dto);
                }
            }
        } else if (0 == dto.getMessageType()) {
            // 当消息类型是评论回复,直接通知给指定用户
            messageRecordService.insert(dto);
        }
    }


}
